<template>
  <page-header-wrapper :title="false">
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8"
                   :sm="24">
              <a-form-item label="用户名">
                <a-input v-model="queryParam.f_fullname"
                         placeholder="请输入用户名" />
              </a-form-item>
            </a-col>
            <a-col :md="8"
                   :sm="24">
              <a-form-item label="手机号码">
                <a-input v-model="queryParam.f_mobile"
                         placeholder="请输入手机号码" />
              </a-form-item>
            </a-col>

            <a-col :md="(!advanced && 8) || 24"
                   :sm="24">
              <span class="table-page-search-submitButtons"
                    :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}">
                <a-button v-auth:ha_user_list
                          type="primary"
                          @click="searchHa_user"
                          icon="search">查询</a-button>
                <a-button v-auth:ha_user_list
                          icon="reload"
                          style="margin-left: 8px"
                          @click="reQuery">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div style="margin-bottom: 16px">
        <a-button v-auth:ha_user_save
                  type="primary"
                  style="margin-left: 8px"
                  @click="handleAdd"
                  icon="plus">添加用户</a-button>
        <a-button v-auth:ha_user_list
                  type="primary"
                  style="margin-left: 8px"
                  @click="exportExcel"
                  icon="export">导出用户</a-button>
        <a-dropdown v-auth:ha_user_del>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-popconfirm :title="'已选择' + selectedRowKeys.length + '项,确定删除吗？'"
                            ok-text="确定"
                            cancel-text="取消"
                            @confirm="delHa_users">
                <a-icon type="delete" />&nbsp;删除
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
          <a-button v-show="selectedRowKeys.length > 0"
                    style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <div class="spin-content">
        已选择&nbsp;
        <a style="font-weight: 600"
           v-text="selectedRowKeys.length"></a>
        项&nbsp;
        <a style="margin-left: 24px"
           @click="() => (selectedRowKeys = [])">清空</a>
      </div>
      <a-table :scroll="{ x: '100%' }"
               :columns=" ucolumns"
               :data-source="udata"
               :pagination="upagination"
               :loading="loading"
               rowKey="id"
               @change="tableChange"
               size="middle"
               :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <span slot="serial"
              slot-scope="text, record, index">
          {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
        </span>
        <span slot="fullnameAndIcon"
              slot-scope="text, record">
          <img :src="record.avatar"
               style="width:40px;height:40px" />
          {{ record.fullname }}
        </span>
        <span slot="gender"
              slot-scope="text, record">
          {{ record.gender === 0 ? '女': record.gender === 1 ? '男' : '' }}
        </span>
        <span slot="operation"
              slot-scope="text, record">
          <template>
            <a v-auth:ha_user_view
               @click="handleEdit(record, true, true)">详情</a>
            <a-divider type="vertical" />
          </template>
          <a-dropdown>
            <a class="ant-dropdown-link">更多
              <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a v-auth:ha_user_save
                   @click="handleEdit(record, false, true)">编辑</a>
              </a-menu-item>
              <a-menu-item>
                <a v-auth:ha_user_save
                   @click="updatePassModal">修改密码</a>
                <a-modal title="修改密码"
                         :visible="updataPassBox"
                         :confirm-loading="confirmLoading"
                         @ok="handleOk(record,updatePassStr, updatePassStr2)"
                         @cancel="handleCancel">
                  <a-input v-model="updatePassStr"
                           placeholder="输入密码" />

                  <a-input style="margin-top:20px"
                           v-model="updatePassStr2"
                           placeholder="再次输入密码" />

                </a-modal>
              </a-menu-item>
              <a-menu-item v-auth:ha_user_save>
                <a-popconfirm title="确定冻结吗？"
                              ok-text="确定"
                              cancel-text="取消"
                              @confirm="delHa_userById(record)">
                  <a-icon slot="icon"
                          type="delete" />
                  <a href="javascript:;">冻结</a>
                </a-popconfirm>
              </a-menu-item>

            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-card>
    <a-drawer :title="isView ? '用户详情' : '用户编辑'"
              :width="720"
              :visible="visible"
              :body-style="{ paddingBottom: '80px' }"
              @close="onClose">
      <edit ref="view"
            @close="onClose"
            @reloadList="searchHa_user"></edit>
    </a-drawer>
  </page-header-wrapper>
</template>

<style lang="less" src="@/style/base.less">
</style>

<script>
import { delHa_users, delHa_user, updatePassword, queryHa_userList, output } from '@/api/base/ha_user'
import edit from '@/views/base/Ha_userEdit'

export default {
  data () {
    return {
      updatePassStr: '',
      updatePassStr2: '',
      advanced: false, // 查询条件是否展开
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      updataPassBox: false,
      ubordered: true, // 表格边框是否显示
      isView: false, // 是否查看
      queryParam: {}, // 查询条件
      selectedRowKeys: [], // 选中的行id
      confirmLoading: false,
      udata: [], // 表格数据
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      ucolumns: [
        {
          title: '序号',
          width: '50px',
          align: 'center',
          fixed: 'left',
          scopedSlots: { customRender: 'serial' },
        },

        {
          title: '用户名',
          dataIndex: 'username',
          width: '20%',
          sorter: (a, b) => String(a.username).localeCompare(String(b.username)),
          align: 'left',
          scopedSlots: { customRender: 'fullnameAndIcon' },
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: '8%',
          sorter: (a, b) => a.gender - b.gender,
          align: 'center',
          scopedSlots: { customRender: 'gender' },
        },
        {
          title: '手机号码',
          dataIndex: 'mobile',
          width: '25%',
          sorter: (a, b) => a.mobile - b.mobile,
          align: 'center',
        },
        {
          title: '座机',
          dataIndex: 'telephone',
          width: '25%',
          sorter: (a, b) => String(a.telephone).localeCompare(String(b.telephone)),
          align: 'center',
        },
        {
          title: '电子邮箱',
          dataIndex: 'email',
          width: '25%',
          sorter: (a, b) => String(a.email).localeCompare(String(b.email)),
          align: 'center',
        },

        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ], // 表头
    }
  },
  created () {
    this.findHa_userList(this.queryParam)
  },
  methods: {
    checkFm (newpass, newpass2) {
      if (newpass != newpass2) {
        this.$message.warn("两次输入密码不一致，请进行核对");
        this.confirmLoading = false;
        return false;
      } else {
        if (newpass.indexOf(" ") != -1) {
          this.$message.warn("密码不能含有空格");
          this.confirmLoading = false;
          return false;
        }
        var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
        if (reg.test(newpass)) {
          this.$message.warn("密码不能含有中文字符");
          this.confirmLoading = false;
          return false;
        }
        //改了密码
        var ls = this.hard(newpass);
        if (ls < 3) {
          this.$message.warn("密码必须包含大写/小写/数字/符号其中至少3种组合, 8位长度以上");
          this.confirmLoading = false;
          return false;
        }
      }
      return true
    },
    hard (s) {
      if (s.length < 8) {
        return 0;
      }
      var ls = 0;
      if (s.match(/([a-z])+/)) {
        ls++;
      }
      if (s.match(/([0-9])+/)) {
        ls++;
      }
    },
    updatePassModal () {
      this.updataPassBox = true
    },
    handleOk (record, updatePassStr, updatePassStr2) {
      this.confirmLoading = true;
      let bool = this.checkFm(updatePassStr, updatePassStr2);
      if (bool) {
        let param = {
          id: record.id,
          newPassword: updatePassStr
        }
        updatePassword(param).then((res) => {
          if (res.code !== 0) {
            this.$message.error('修改密码失败')
            this.confirmLoading = false
          } else {
            this.$message.success('修改密码成功')
            this.$emit('reloadList')
            this.updataPassBox = false;
            this.confirmLoading = false
          }
        })
        this.updatePassStr = ''
        this.updatePassStr2 = ''
      }
    },
    handleCancel (e) {
      console.log('Clicked cancel button');
      this.updataPassBox = false;
    },
    /**
     *  查询用户列表
     */
    findHa_userList (queryParam) {
      console.log('queryParam', queryParam)
      const a = Date.now()
      console.log('queryParam', queryParam)
      queryHa_userList(queryParam).then((res) => {
        this.loading = true
        console.log('queryHa_userList:', res.data)
        this.udata = res.data.records
        // 将当前页码和数量与后台绑定
        this.upagination.total = res.data.total
        this.upagination.current = res.data.current
        this.upagination.pageSize = res.data.size
        // 如果查询时间太短就给一个0.5秒的加载效果
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          this.loading = false
        }
      })
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      this.queryParam = {}
      this.findHa_userList(this.queryParam)
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange (pagination, filters, sorter, { currentDataSource }) {
      console.log('tableChange', pagination)
      console.log('filters', filters)
      console.log('sorter', sorter)
      console.log('{ currentDataSource }', { currentDataSource })
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findHa_userList(this.queryParam)
    },
    /**
     * 查询
     */
    searchHa_user () {
      // 查询时将当前页码重置为1，否则会出现有数据但不显示的问题
      this.queryParam.pageNumber = 1
      // this.upagination.current = 1
      this.findHa_userList(this.queryParam)
    },
    /**
     * 选中行数据时触发
     */
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 打开抽屉
     */
    showDrawer () {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose () {
      this.visible = false
    },
    /**
     * 进入新增页面
     */
    handleAdd () {
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.hidden = false
        this.$refs.view.resetHa_user()
      }, 10)
    },
    /**
     * 进入编辑页面
     */
    handleEdit (res, isView, hidden) {
      this.isView = isView
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findHa_userById(res.id, isView, hidden)
      }, 10)
    },
    /**
     * 冻结用户
     */
    delHa_userById (res) {
      delHa_user(res.id).then((res) => {
        console.log('delHa_user:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_user()
          this.$message.success('冻结成功')
        }
      })
    },
    /**
     * 批量删除用户
     */
    delHa_users () {
      delHa_users(this.selectedRowKeys.toString()).then((res) => {
        console.log('delHa_users:', res)
        if (res.code !== 0) {
          this.$message.success(res.msg)
        } else {
          this.selectedRowKeys = []
          this.searchHa_user()
          this.$message.success('删除成功')
        }
      })
    },
    /**
     *  导出Excel
     */
    exportExcel () {
      output(this.queryParam)
        .then((response) => {
          var blob = new Blob([response])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '用户.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch(function () {
          console.log(error)
        })
    },
  },
  components: {
    edit,
  },
}
</script>